<template>
  <div class="race-page">
    <div class="header">
      <div class="round-info">
        <span class="round-text">第 {{ roundIndex+1 }} 轮</span>
        <span class="timer">剩余时间: {{ minutes }}:{{ seconds < 10 ? '0' + seconds : seconds }}</span>
      </div>
      <div class="btn">
        <!-- <el-button type="primary" @click="dialogVisible = true">确定</el-button> -->
        <el-button type="primary" @click="nextRound" icon="el-icon-arrow-right">
          下一轮
        </el-button>
      </div>
    </div>

    <el-divider />

    <!-- 管理员界面 -->
    <el-card v-if="role === 'sa' || role === 'teacher' || role === 'student'" class="admin-panel">
      <div class="round-info">
        <!-- <span>总分: {{ totalScore }}</span> -->
      </div>
      <!-- <el-button
        type="primary"
        size="large"
        @click="startNextRound"
        :disabled="raceStarted"
        class="start-button"
      >
        {{ raceStarted ? "抢答中..." : "开始抢答" }}
      </el-button> -->
      <div v-if="winner" class="winner-info">
        <el-alert
          title="抢答成功！"
          type="success"
          :description="`抢答者：${winner.name}`"
        />
        <!-- 显示考生提交的信息 -->
        <div v-if="submittedAnswer" class="submitted-answer">
          <h3>考生提交的信息：</h3>
          <p>选中人员：{{ submittedAnswer.selectedPerson }}</p>
          <p>姓名：{{ submittedAnswer.name }}</p>
          <p>所住小区：{{ submittedAnswer.community }}</p>
        </div>
      </div>
      <!-- 显示辖区人员头像 -->
      <div class="people-grid">
        <div
          v-for="person in popQuList"
          :key="person.id"
          class="person-card"
          :class="{ 
            'selected': selectPopQu.includes(person),
            'disabled': selectedHistory.includes(person.id)
          }"
          @click="selectPerson(person)"
        >
          <div class="avatar-container">
            <img :src="person.image"  class="avatar" />
          </div>
          <div class="serial-number">
            <el-tag size="medium" type="info">编号：{{ person.id }}</el-tag>
          </div>
        </div>
      </div>
      <!-- <div class="next-round">
        <el-button type="primary" @click="fetchData('123')" icon="el-icon-arrow-right">
          下一轮
        </el-button>
      </div> -->
    </el-card>
    <div class="next-round">
        <!-- <el-button type="primary" @click="nextRound" icon="el-icon-arrow-right">
          下一轮
        </el-button> -->
        <el-button type="primary" @click="dialogVisible = true">确定</el-button>
      </div>
    <!-- 考生界面 -->
    <!-- <el-card v-if="role === 'student'" class="student-panel">
      <div class="student-info">
        <span>姓名：{{ studentName }}</span>
        <span>编号：{{ studentId }}</span>
        <span>当前得分：{{ studentScore }}</span>
      </div>
      <div class="people-grid">
        <div
          v-for="person in popQuList"
          :key="person.id"
          class="person-card"
          :class="{ selected: studentAnswerForm.selectedPerson === person.id }"
          @click="selectPerson(person)"
        >
          <div class="avatar-container">
            <img :src="person.image" :alt="person.name" class="avatar" />
          </div>
        </div>
      </div>
      <el-alert
        v-if="!raceStarted"
        title="等待管理员开始抢答..."
        type="info"
        show-icon
        class="info-alert"
      />
      <el-button
        v-if="raceStarted && !answered"
        type="success"
        size="large"
        @click="answerRace"
        class="answer-button"
      >
        抢答
      </el-button>
      <el-alert
        v-if="answered && !isWinner"
        title="抢答结果：失败"
        type="warning"
        show-icon
        class="result-alert"
      />
      <el-alert
        v-if="isWinner && !studentAnswerForm.selectedPerson"
        title="抢答成功！请选择一个头像继续作答"
        type="success"
        show-icon
        class="result-alert"
      />
      <el-form
        v-if="isWinner && studentAnswerForm.selectedPerson && !studentSubmitted"
        class="student-answer-form"
        :model="studentAnswerForm"
        label-width="100px"
      >
        <el-form-item label="姓名">
          <el-input v-model="studentAnswerForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="所住小区">
          <el-input
            v-model="studentAnswerForm.community"
            placeholder="请输入小区"
          />
        </el-form-item>
        <el-button type="primary" @click="submitStudentAnswer">提交答案</el-button>
      </el-form>
      <el-alert
        v-if="studentSubmitted"
        title="提交成功！等待下一轮抢答..."
        type="success"
        show-icon
        class="submit-success-alert"
      />
    </el-card> -->

    <el-dialog
      :visible.sync="dialogVisible"
      width="100%"
      :before-close="handleClose"
      :fullscreen="true"
    >
      <el-row :gutter="20" type="flex" justify="center" align="middle">
        <el-col :span="12" v-for="item in selectPopQu" :key="item.id">
          <el-card class="comparison-card">
            <div class="name-container">
              <transition name="fade">
                <h1 v-if="showAnswer">{{ item.name }}</h1>
              </transition>
              <transition name="fade">
                <h1 v-if="showAnswer">{{ item.address }}</h1>
              </transition>
              <!-- <transition name="fade">
                <p v-if="showAnswer && roundArr[roundIndex] === 'important'">管控类型：{{ item.content }}</p>
              </transition>
              <transition name="fade">
                <p v-if="showAnswer && roundArr[roundIndex] === 'important'">当前去向：{{ item.job }}</p>
              </transition> -->
            </div>
            <div class="image-container">
              <img :src="item.image" alt="">
            </div>
            <div class="dialog-serial-number">
              <el-tag size="medium" effect="dark" type="warning">编号：{{ item.id }}</el-tag>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <div class="dialog-footer">
        <el-button type="primary" @click="toggleAnswer">
          {{ showAnswer ? '隐藏答案' : '显示答案' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { saveRob, saveQuick } from "@/api/exam/exam";
import { fetchQucikDetail } from "@/api/paper/exam";

export default {
  name: "Population",

  data() {
    return {
      role: "student",
      raceStarted: false,
      answered: false,
      winner: null,
      studentId: this.generateRandomId(),
      studentName: this.generateRandomName(),
      totalScore: 0,
      studentScore: 0,
      studentAnswerForm: {
        selectedPerson: "",
        name: "",
        community: "",
      },
      submittedAnswer: null,
      studentSubmitted: false,
      popQuList: [],
      timerId: null,
      selectPersonId: null,
      selectPopQu: [],
      dialogVisible: false,
      showAnswer: false,
      selectedHistory: [],
      roundArr:['roundfz','roundcz','roundld'],
      roundIndex:0,
      minutes: 1,
      seconds: 0,
      countdownTimer: null
    };
  },

  computed: {
    isWinner() {
      return this.winner && this.winner.id === this.studentId;
    },
  },

  created() {
    this.role = this.$store.state.user.roles[0];

    const params = this.roundArr[0];
    this.fetchData(params);
    this.startCountdown();

    // if (this.role === "student") {
    //   this.startPolling();
    // }
  },

  methods: {
    fetchData(id) {
      const params = {id:this.roundArr[this.roundIndex]}
      fetchQucikDetail(params).then((res) => {
        this.popQuList = res.data.popQu;
      });
    },

    startCountdown() {
      this.minutes = 1;
      this.seconds = 0;
      if(this.countdownTimer) {
        clearInterval(this.countdownTimer);
      }
      this.countdownTimer = setInterval(() => {
        if(this.seconds > 0) {
          this.seconds--;
        } else if(this.minutes > 0) {
          this.minutes--;
          this.seconds = 59;
        } else {
          clearInterval(this.countdownTimer);
          this.$message.warning('时间到！');
        }
      }, 1000);
    },

    nextRound() {
      if(this.roundIndex < this.roundArr.length-1) {
        this.fetchData();
        this.startCountdown();
        this.roundIndex++;
      } else {
        this.$message.warning('已经是最后一轮了');
      }
    },

    generateRandomId() {
      return Math.random().toString(36).substr(2, 9);
    },

    generateRandomName() {
      return this.$store.state.user.name;
    },

    startNextRound() {
      saveRob().then((res) => {
        console.log(res);
        this.raceStarted = res.data;
        if (this.raceStarted) {
          this.startPolling();
        }
      });
    },

    startPolling() {
      this.timerId = setInterval(() => {
        if (this.role === "sa" || this.role === "teacher") {
          this.pollAdminStatus();
        } else {
          this.pollStudentStatus();
        }
      }, 1000);
    },

    pollAdminStatus() {
      saveQuick().then((res) => {
        this.raceStarted = res.data;
        if (!res.data) {
          this.winner = { name: res.msg };
          clearInterval(this.timerId);
          this.raceStarted = false;
        }
      });
    },

    pollStudentStatus() {
      saveRob().then((res) => {
        console.log(res);
        this.raceStarted = res.data;
        if (this.raceStarted) {
          this.answered = false;
          this.studentSubmitted = false;
          this.studentAnswerForm = {
            selectedPerson: "",
            name: "",
            community: "",
          };
        }
      });
    },

    answerRace() {
      if (!this.raceStarted) return;
      saveQuick().then((res) => {
        this.raceStarted = res.data;
        this.answered = true;
        if (!res.data) {
          this.winner = {
            id: this.studentId,
            name: this.studentName,
          };
        }
      });
    },

    selectPerson(person) {
      // if (this.selectedHistory.includes(person.id)) {
      //   return;
      // }

      this.selectPersonId = person.id;
      this.selectPopQu.push(person);

      if (this.selectPopQu.length > 2) {
        // this.dialogVisible = true;
        this.selectPopQu.splice(0,1)
      }

      if (this.isWinner && !this.studentSubmitted) {
        this.studentAnswerForm.selectedPerson = person.id;
      }
    },

    handleClose() {
      this.selectPopQu.forEach(person => {
        if (!this.selectedHistory.includes(person.id)) {
          // this.selectedHistory.push(person.id);
        }
      });
      this.selectPopQu = [];
      this.dialogVisible = false;
      this.showAnswer = false;
    },

    toggleAnswer() {
      this.showAnswer = !this.showAnswer;
    },

    submitStudentAnswer() {
      if (
        this.isWinner &&
        !this.studentSubmitted &&
        this.studentAnswerForm.selectedPerson
      ) {
        this.submittedAnswer = { ...this.studentAnswerForm };
        this.$emit("submit-student-answer", this.submittedAnswer);
        this.studentSubmitted = true;
        this.$message.success("提交成功！");
        this.startPolling();
      }
    },
  },
  watch: {},

  beforeDestroy() {
    if (this.timerId) {
      clearInterval(this.timerId);
    }
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
    }
  },
};
</script>

<style scoped>
.race-page {
  padding: 20px;
  background-color: #f9f9f9;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  /* margin-bottom: 20px; */
}

.round-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.timer {
  font-size: 24px;
  color: #f56c6c;
  font-weight: bold;
}

.round-text {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.btn {
  display: flex;
  justify-content: flex-end;
}

.el-divider{
  margin: 1px;
}

.admin-panel,
.student-panel {
  margin: 0px auto;
  max-width: 1200px;
  /* padding: 10px; */
  background-color: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.round-info {
  display: flex;
  justify-content: space-between;
  /* margin-bottom: 20px; */
  font-size: 16px;
  color: #666;
}

.people-grid {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 30px;
  margin: 20px 0;
}

.person-card {
  text-align: center;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.person-card.selected {
  border-color: #409eff;
  box-shadow: 0 0 10px rgba(64, 158, 255, 0.5);
}

.person-card.disabled {
  opacity: 0.5;
  cursor: not-allowed;
  background-color: #f5f5f5;
}

.avatar-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  margin-bottom: 10px;
}

.person-card .avatar {
  width: 100%;
  height: 100%;
  /* border-radius: 50%; */
  object-fit: cover;
}

.serial-number {
  margin-top: 8px;
  display: flex;
  justify-content: center;
}

.next-round {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.student-answer-form {
  margin-top: 20px;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 8px;
}

.student-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  font-size: 16px;
  color: #666;
}

.start-button,
.answer-button {
  display: block;
  width: 100%;
  margin-top: 20px;
}

.winner-info {
  margin-top: 20px;
}

.info-alert,
.result-alert,
.submit-success-alert {
  margin-top: 20px;
}

.submitted-answer {
  margin-top: 20px;
  padding: 10px;
  background-color: #f0f9eb;
  border: 1px solid #e1f3d8;
  border-radius: 4px;
}

.comparison-card {
  margin: 20px;
  text-align: center;
  padding: 20px;
}

.image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
  margin: 20px 0;
}

.image-container img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.name-container {
  height: 60px;
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: center;
  margin-top: 20px;
}

.dialog-serial-number {
  margin-top: 15px;
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}
</style>
